import React, { useEffect, useState } from 'react';
import './index.less';
import { Row, Col, Divider, Carousel, Button } from 'antd';
import echarts from 'echarts';
import {
    getLiftInfoApi,
    getLocationApi,
    getWeatherApi,
    IWeather,
    getLiftImageApi,
    getLiftMaintanceApi,
    getLiftAppDataApi,
    getLiftMessageApi,
    getBottomInfoApi,
} from 'api/index';
import { connectWebViewJavascriptBridge } from 'utils/jsBridge';
import vconsole from 'vconsole';
import moment from 'moment';
const KEY = '924192e5a0c3fdbd469cabd4a7c83515';
const initalWeather = {
    adcode: 330110,
    city: '',
    humidity: 0,
    province: '',
    reporttime: '',
    temperature: 28,
    weather: '',
    winddirection: '东南',
    windpower: '≤3',
};
interface IGps {
    lng: number;
    lat: number;
}
interface IMaintenance {
    lastMaintenanceName: string;
    lastMaintenanceTime: number;
    lastMaintenanceMessage: string;
    lastCleanName: string;
    lastCleanTime: number;
}
const Page1 = () => {
    const [weatherInfo, setWeatherInfo] = useState<IWeather>(initalWeather); // 天气
    const [gps, setGps] = useState<IGps>(); // gps信息
    const [wifiConnected, setWifiConnected] = useState(false); // wifi是否连接
    const [selectedFloors, setSelectedFloors] = useState<string[]>([]); // 选中的楼层
    const [maintenanceInfo, setMaintenanceInfo] = useState<IMaintenance>(); // 电梯维护信息
    const [liftInfo, setLiftInfo] = useState<any>(); // 电梯信息
    const [deviceId, setDeviceId] = useState(); // 设备ID
    const [advertises, setAdvertises] = useState<string[]>([require('assets/images/default.jpg')]);
    const [bottomInfo, setBottomInfo] = useState<any>(); // 底部信息
    const [liftStatus, setLiftStatus] = useState('1'); // 电梯状态
    const [doorStatus, setDoorStatus] = useState('1'); // 电梯门状态
    const [stopFloor, setStopFloor] = useState('1'); // 电梯停靠楼层
    const [alarm, setAlarm] = useState('无警告'); // 报警信息
    const [carrFloors, setCarrFloors] = useState<any[]>([]);
    const [msgs, setMsgs] = useState<any>([]);
    useEffect(() => {
        if (window.location.hostname === '120.78.80.132') {
            
        }
        new vconsole();
        setTimeout(() => {
            let dom = document.getElementById('__vconsole')
            if (dom) {
                dom.style.display = 'none'
            }
        })
        
    }, [])
    const setDebug = () => {
        let dom = document.getElementById('__vconsole')
        if (!dom) return
        let display = dom.style.display
        if (display === 'none') {
            dom.style.display = 'block'
            window.WebViewJavascriptBridge?.callHandler('setDebug', JSON.stringify({ isDebug: 'true' }))
        } else {
            dom.style.display = 'none'
            window.WebViewJavascriptBridge?.callHandler('setDebug', JSON.stringify({ isDebug: 'false' }))
        }
    }
    useEffect(() => {
        // getWeather(120.24, 30.409974);
        let timer = setInterval(() => {
            let hourMin = moment().format('HH:mm');
            let monthDay = moment().format('MM月DD日');
            setWeatherInfo({ ...weatherInfo, hourMin, monthDay });
            let second = moment().second();
            let min = moment().minute();
            if (gps && second === 0 && [0, 10, 20, 30, 40, 50].indexOf(min) > -1) {
                getWeather(gps.lng, gps.lat);
            }
        }, 1000);
        connectWebViewJavascriptBridge((bridge: any) => {
            /** 获取wifi状态 */
            bridge.callHandler('getWiFiStatus', '', (res: any) => {
                res = JSON.parse(res);
                console.log('getWiFiStatus', res);
                setWifiConnected(res.connected == 1 ? true : false);
            });
            /** 获取gps信息 */
            bridge.callHandler('getLocationGPS', '', (res: any) => {
                res = JSON.parse(res);
                console.log('getLocationGPS', res);
                setGps({ lng: res.longitude, lat: res.latitude });
                if (gps) {
                    getWeather(gps.lng, gps.lat);
                }
            });
            /** 获取电梯设备号 */
            bridge.callHandler('getDeviceInfo', '', (res: any) => {
                res = JSON.parse(res);
                console.log('getDeviceInfo', res);
                setDeviceId(res.deviceId);
            });
            /** 获取电梯状态 */
            bridge.registerHandler('registerElevatorRunStatusListener', function (data: any, responseCallback: any) {
                console.log('registerElevatorRunStatusListener', data, responseCallback);
                if (responseCallback) {
                    responseCallback();
                }
                handleRunStatus(data, carrFloors);
            });
            /** 获取当前选中电梯楼层 */
            bridge.registerHandler('registerElevatorFloorStatusListener', function (
                data: string,
                responseCallback: any,
            ) {
                console.log('registerElevatorFloorStatusListener', data, responseCallback);
                let res = data.slice(2, data.length - 1).split(',').filter(item => item !== '');
                setSelectedFloors(res);
                if (responseCallback) {
                    responseCallback();
                }
            });
            return () => {
                clearInterval(timer);
            };
        });
    }, [carrFloors]);
    const handleRunStatus = (value: string, carrFloors: any) => {
        console.log(value);
        let arr = value.split(':');
        if (arr[0] === '!DIANTI_STATE') {
            // 电梯向上2、下运行3，停止1
            setLiftStatus(arr[1].split('#')[0]);
        } else if (arr[0] === '!DOOR_STATE') {
            // 电梯门开2 关1
            setDoorStatus(arr[1].split('#')[0].split(',')[0]);
        } else if (arr[0] === '!STOP_FLOOR') {
            // 停靠楼层
            setStopFloor(arr[1].split('#')[0]);
        } else if (arr[0] === '!CARR') {
            let floor = arr[1].split(',')[1];
            let time = Math.floor((Number(arr[1].split(',')[3]) - Number(arr[1].split(',')[2])));
            setCarrFloors([{ floor, time }, ...carrFloors]);
        } else if (arr[0] === '!ALARM') {
            let alarmMap: any = {
                1: '困人',
                2: '开门走车',
                3: '开门超时',
                4: '关门被打断',
            };
            let temp = arr[1].split('#')[0].split(',');
            let alarm = `${temp[1]}楼：${alarmMap[temp[0]]}`;
            setAlarm(alarm);
            setTimeout(() => {
                setAlarm('无警告');
            }, 8 * 1000);
        }
    };
    /** 初始化饼图 */
    const initPie = (healthyScore: number) => {
        let option = {
            color: ['rgba(8, 102, 178)', 'rgba(110, 221, 27)'],
            title: {
                x: 'center',
                top: '30',
                // y: 'center',
                text: String(healthyScore),
                textStyle: {
                    fontSize: 64,
                    color: '#000',
                    fontWeight: 'bold',
                },
                subtext: '健康度',
                subtextStyle: {
                    fontSize: 20,
                    color: 'red',
                    fontWeight: '800',
                },
            },
            tooltip: {
                show: false,
            },
            legend: {
                show: false,
            },
            series: [
                {
                    type: 'pie',
                    radius: ['65%', '90%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center',
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '30',
                            fontWeight: 'bold',
                        },
                    },
                    labelLine: {
                        show: false,
                    },
                    data: [{ value: healthyScore }, { value: 100 - healthyScore }],
                },
            ],
        };
        let dom: any = document.getElementById('pie');
        if (!dom) return;
        let chart = echarts.init(dom);
        chart.setOption(option as any);
    };
    /** 初始化柱状图 */
    const initLine = (data: any, drawType: any) => {
        function calcFixed(value: any, count: any, unit: any, len: any) {
            return value % count < count / 10 ? (value / count).toFixed(0) + unit : (value / count).toFixed(len) + unit;
        }
        let option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999',
                    },
                },
            },
            grid: {
                top: 20,
                bottom: 30,
                left: 50,
            },
            xAxis: [
                {
                    type: 'category',
                    data: data.map(function (d: any) {
                        return d.xname;
                    }),
                    axisPointer: {
                        type: 'shadow',
                    },
                },
            ],
            yAxis: [
                {
                    type: 'value',
                    splitNumber: 3,
                    axisLabel: {
                        fontSize: 8,
                        formatter: function (value: any) {
                            if (value >= 1000 && value < 10000) {
                                value = calcFixed(value, 1000, '千', 1);
                            } else if (value >= 10000 && value < 100000) {
                                value = calcFixed(value, 10000, '万', 1);
                            } else if (value >= 100000 && value < 1000000) {
                                value = calcFixed(value, 100000, '百万', 2);
                            }
                            return value;
                        },
                    },
                },
            ],
            series: [
                {
                    name: drawType.name,
                    type: 'bar',
                    barMaxWidth: 10,
                    itemStyle: {
                        normal: {
                            barBorderRadius: [7.5, 7.5, 0, 0],
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    {
                                        offset: 0,
                                        color: 'rgba(84,79,235, 0.6)',
                                    },
                                    {
                                        offset: 1,
                                        color: 'rgba(84,79,235, 0)',
                                    },
                                ],
                            },
                        },
                    },
                    data: data.map(function (d: any) {
                        return d[drawType.key];
                    }),
                },
            ],
        };
        let dom: any = document.getElementById('line');
        if (!dom) return;
        let chart = echarts.init(dom);
        chart.setOption(option as any);
    };
    useEffect(() => {
        if (!deviceId) return;
        // deviceId  'tgg_33010001_008'
        let timer: any;
        function getLiftImage() {
            getLiftImageApi({ liftSn: deviceId || '33010001_4' }).then((res) => {
                if (!res.data) return;
                setAdvertises(res.data.urls || []);
            });
        }
        function getLiftInfo() {
            getLiftInfoApi({ deviceSn: deviceId }).then((res) => {
                console.log('liftInfo', res);
                if (!res.data) return;
                initPie(res?.data?.healthyScore);
                const starLength = Math.floor(res.data?.totalCommentScore / res.data?.totalCommentCount);
                res.data.starArr = new Array(starLength).fill(1);
                setLiftInfo(res.data);
            });
        }
        function getLiftMaintenance() {
            getLiftMaintanceApi({ deviceSn: deviceId }).then((res) => {
                console.log('维护信息', res);
                if (!res.data) return;
                setMaintenanceInfo(res.data);
            });
        }
        function getLiftAppData() {
            getLiftAppDataApi({ deviceSn: deviceId }).then((res) => {
                console.log('appData', res);
                if (!res.data) return;
                const barObj = [
                    { name: '本月运行次数', key: 'runCount' },
                    { name: '本月运行距离（单位米）', key: 'runDistance' },
                    { name: '本月门开关次数', key: 'doorOpenCount' },
                    { name: '本月最高速度（单位米/秒）', key: 'averageSpeed' },
                ];
                initLine(res.data, barObj[0]);
                let index = 0;
                timer = setInterval(() => {
                    index++;
                    const drawType = barObj[index % barObj.length];
                    let titleDom = document.getElementById('lineTitle');
                    if (titleDom) {
                        titleDom.innerHTML = drawType.name;
                    }
                    initLine(res.data, drawType);
                }, 10 * 1000);
            });
        }
        function getBottomInfo() {
            getBottomInfoApi({ deviceSn: deviceId }).then((res) => {
                console.log('bottom info', res);
                if (!res.data) return;
                setBottomInfo(res.data);
            });
        }
        function getLiftMessage() {
            getLiftMessageApi({ deviceSn: deviceId }).then((res) => {
                console.log('message', res);
                if (!res.data) return;
                setMsgs(res.data);
            });
        }
        getLiftImage();
        getLiftInfo();
        getLiftMaintenance();
        getLiftAppData();
        getBottomInfo();
        getLiftMessage();
        let refresTimer = setInterval(() => {
            let hour = moment().hour();
            let second = moment().second();
            let min = moment().minute();
            if (second !== 0 || min !== 0) return;
            getLiftInfo(); // 每小时刷新
            getLiftMaintenance();
            if (hour === 0) {
                // 凌晨刷新
                getLiftImage();
                getBottomInfo();
                getLiftAppData();
                getLiftMessage();
            }
        }, 1000);
        return () => {
            clearInterval(timer);
            clearInterval(refresTimer);
        };
    }, [deviceId]);
    useEffect(() => {
        // initLine();
    }, []);
    const imageloadError = (e: any) => {
        e.target.onerror = null;
        e.target.src = require('assets/images/default.jpg');
    };
    /** 获取gps */
    const getWeather = async (lng: number, lat: number) => {
        const location = await getLocationApi({ key: KEY, location: `${lng},${lat}` });
        console.log('location', location?.regeocode);
        const weatherParams = { key: KEY, city: location?.regeocode?.addressComponent?.adcode };
        const weather = await getWeatherApi(weatherParams);
        console.log('weather', weather?.lives?.[0]);
        setWeatherInfo(weather?.lives?.[0]);
    };
    return (
        <div className="page1">
            <Row onClick={setDebug}>
                <Col span={12} style={{ padding: 20, display: 'flex' }}>
                    <img src={require('assets/images/logo_hithink_v2.png')} alt="" className="mr20" width="40%" />
                    <img src={require('assets/images/logo_tigogo_top.png')} alt="" className="mr20" width="30%" />
                    {wifiConnected && <img src={require('assets/images/icon_wifi.png')} alt="" />}
                </Col>
                <Col
                    span={12}
                    className="flex-between"
                    style={{ backgroundImage: `url(${require('assets/images/bg_top_weather.png')})`, color: '#fff' }}
                >
                    <div className="ml30 text-left">
                        <div>天气：{weatherInfo?.weather}</div>
                        <div>气温：{weatherInfo?.temperature}°C</div>
                    </div>
                    <div className="mr30 text-right">
                        <div className="bold font-20">{weatherInfo?.hourMin}</div>
                        <div>{weatherInfo?.monthDay}</div>
                    </div>
                </Col>
            </Row>
            <div style={{ height: 100 }} className="flex-align">
                {selectedFloors.map((item) => (
                    <div className="selected-floor" key={item}>
                        {item}
                    </div>
                ))}
                {/* <Button onClick={() => handleRunStatus('!DIANTI_STATE:1#1')}>停止</Button>
                <Button onClick={() => handleRunStatus('!DIANTI_STATE:2#1')}>向上</Button>
                <Button onClick={() => handleRunStatus('!DIANTI_STATE:3#1')}>向下</Button>
                <Button onClick={() => handleRunStatus('!DOOR_STATE:2,2,3#1')}>开门</Button>
                <Button onClick={() => handleRunStatus('!DOOR_STATE:1,2,3#1')}>关门</Button>
                <Button onClick={() => handleRunStatus(`!STOP_FLOOR:${Math.floor(Math.random() * 10)}#1`)}>停靠</Button>
                <Button onClick={() => handleRunStatus(`!CARR:${Math.floor(Math.random() * 10)},${Math.floor(Math.random() * 10)},3333,${12000},${20000},${2200}#12324`)}>经过</Button>
                <Button onClick={() => handleRunStatus('!ALARM:1,6#1')}>停止</Button> */}
            </div>
            <Carousel autoplay dots={false} autoplaySpeed={8000}>
                {advertises.map((url) => (
                    <div key={url}>
                        <img src={url} alt="" width="100%" onError={(e: any) => imageloadError(e)} />
                    </div>
                ))}
            </Carousel>
            <div className="content">
                <Row className="flex mb20" align="middle" style={{ backgroundColor: '#fff' }}>
                    <Col span={4} style={{ color: '#4191e4', backgroundColor: 'rgb(213, 238, 255)', padding: '40px 20px' }}>
                        <div>梯狗狗语音导航服务</div>
                        <div>你可以说出以下内容</div>
                        <div>梯狗狗为您提供服务</div>
                    </Col>
                    <Col span={2} style={{  }}>
                        <img src={require('assets/images/icon_tip_floor.png')} alt="" width="100%" />
                    </Col>
                    <Col span={18} className="text-left" style={{ padding: '40px 20px' }}>
                        <div className="text-left" style={{ fontSize: 32 }}>
                            <Divider type="vertical" />
                            语音控制
                        </div>
                        <div>你可以直接呼喊‘X楼'来控制电梯</div>
                    </Col>
                </Row>
                <Row className="mb20" align="middle" style={{ padding: 20, backgroundColor: '#fff' }} >
                    <Col span={8}>
                        <img src={require('assets/images/message_tigogo.png')} alt="" width="100%" />
                    </Col>
                    <Col span={16} className="text-right pr20 font-32">
                        {/* <Divider type="vertical" /> */}
                        {msgs.length > 0 ? (
                            <Carousel dotPosition="right" dots={false} autoplaySpeed={8000} autoplay>
                                {msgs.map((msg: any, index: number) => (
                                    <div key={index} className="font-32">
                                        {msg.message}
                                    </div>
                                ))}
                            </Carousel>
                        ) : (
                            <div>暂无信息</div>
                        )}
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <div className="alarm flex-center">
                            <img className="img-16 mr10" src={require('assets/images/icon_sos.png')} alt="" />
                            <span className="font-16">{alarm}</span>
                        </div>
                        <Row>
                            <Col span={14}>
                                {liftStatus !== '2' && (
                                    <img
                                        className="mb10"
                                        src={require('assets/images/elevator_move_up_pause.png')}
                                        alt=""
                                        width="100%"
                                    />
                                )}
                                {liftStatus === '2' && (
                                    <img
                                        className="mb10"
                                        src={require('assets/images/elevator_move_up.gif')}
                                        alt=""
                                        width="100%"
                                    />
                                )}
                                {doorStatus === '1' && (
                                    <img
                                        style={{ height: 400 }}
                                        src={require('assets/images/elevator_door_close.png')}
                                        alt=""
                                        width="100%"
                                    />
                                )}
                                {doorStatus === '2' && (
                                    <img
                                        style={{ height: 400 }}
                                        src={require('assets/images/elevator_door_open.png')}
                                        alt=""
                                        width="100%"
                                    />
                                )}
                                {liftStatus !== '3' && (
                                    <img
                                        className="mt10"
                                        src={require('assets/images/elevator_move_down_pause.png')}
                                        alt=""
                                        width="100%"
                                    />
                                )}
                                {liftStatus === '3' && (
                                    <img
                                        className="mt10"
                                        src={require('assets/images/elevator_move_down.gif')}
                                        alt=""
                                        width="100%"
                                    />
                                )}
                            </Col>
                            <Col span={10} style={{ padding: 20 }}>
                                <div style={{ height: 140, fontSize: 64, color: '#4191e4', textAlign: 'center' }}>{stopFloor}</div>
                                {carrFloors.slice(0, 6).map((item, index) => (
                                    <Row className="pass-floor" key={index}>
                                        <Col span={12}>{item.floor}层</Col>
                                        <Col span={12}>{item.time}s</Col>
                                    </Row>
                                ))}
                            </Col>
                        </Row>
                    </Col>
                    <Col span={12} style={{ padding: 10 }}>
                        <Row style={{ borderBottom: '5px solid #4191e4', paddingBottom: 10 }}>
                            <Col span={6} style={{ color: 'red' }}>
                                {liftInfo?.residentialDistrictName}
                            </Col>
                            <Col span={6} style={{ color: 'red' }}>
                                {liftInfo?.name}
                            </Col>
                            <Col span={6} style={{ fontWeight: 'bold' }}>
                                {liftInfo?.brandName}
                            </Col>
                            <Col span={6} style={{ fontWeight: 'bold' }}>
                                {liftInfo?.setupDate && moment(liftInfo.setupDate).format('YYYY/MM')}
                            </Col>
                        </Row>
                        <Row className="mb20" style={{ padding: 10 }}>
                            <Col span={12} className="text-left">
                                <Row style={{ padding: 10 }}>
                                    <Col span={4}>
                                        <img src={require('assets/images/icon_by.png')} alt="" width="100%" />
                                    </Col>
                                    <Col span={20} className="pl20">
                                        <div>{maintenanceInfo?.lastMaintenanceName}</div>
                                        <div>
                                            时间：
                                            {maintenanceInfo?.lastMaintenanceTime &&
                                                moment(maintenanceInfo?.lastMaintenanceTime).format('MM月DD日')}
                                        </div>
                                    </Col>
                                </Row>
                                <Row style={{ padding: 10 }}>
                                    <Col span={4}>
                                        <img src={require('assets/images/icon_bj.png')} alt="" width="100%" />
                                    </Col>
                                    <Col span={20} className="pl20">
                                        <div>{maintenanceInfo?.lastCleanName}</div>
                                        <div>
                                            时间：
                                            {maintenanceInfo?.lastCleanTime &&
                                                moment(maintenanceInfo?.lastCleanTime || '').format('MM月DD日')}
                                        </div>
                                    </Col>
                                </Row>
                                <Row style={{ padding: 10 }} align="middle">
                                    <Col span={4}>
                                        <img src={require('assets/images/icon_hp.png')} alt="" width="100%" />
                                    </Col>
                                    <Col span={20} className="pl20">
                                        {liftInfo?.starArr.map(({}, index: number) => (
                                            <img
                                                key={index}
                                                src={require('assets/images/star.png')}
                                                alt=""
                                                width="30"
                                                className="mr10"
                                            />
                                        ))}
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={12} id="pie"></Col>
                        </Row>
                        <div id="lineTitle" className="text-left">
                            本月运行次数
                        </div>
                        <div id="line" style={{ width: '100%', height: 250 }}></div>
                    </Col>
                </Row>
                <Row style={{ padding: 20 }}>
                    <Col span={4}>
                        <img src={require('assets/images/tigogo-logo.png')} alt="" width="100%" />
                    </Col>
                    <Col span={16} className="pl20">
                        <Row className="text-left" style={{ borderBottom: '2px solid' }}>
                            <Col span={20} style={{ color: 'blue', fontSize: 24 }}>
                                <Row align="middle" style={{ padding: 5 }}>
                                    <Col span={2}>
                                        <img src={require('assets/images/zuoji.png')} alt="" width="100%" />
                                    </Col>
                                    <Col span={22} className="pl20">
                                        本楼安保：{bottomInfo?.phone?.[0]}
                                    </Col>
                                </Row>
                                <Row align="middle" style={{ padding: 5 }}>
                                    <Col span={2}>
                                        <img src={require('assets/images/zuoji.png')} alt="" width="100%" />
                                    </Col>
                                    <Col span={22} className="pl20">
                                        救援平台：{bottomInfo?.phone?.[1]}
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={4} className="pt20 font-16" style={{ color: 'red' }}>
                                <div>微信扫一扫</div>
                                <div>关注梯狗狗</div>
                                <div>安心乘电梯</div>
                            </Col>
                        </Row>
                        <div className="text-center mt10 font-16 mb10">
                            技术支持：浙江核心同花顺网络股份信息有限公司
                        </div>
                        <div className="font-16 text-center">杭州市余杭区五常街道同顺街19号 电话0571-88911818</div>
                    </Col>
                    <Col span={4}>
                        <img src={bottomInfo?.qrCodeUrl} alt="" width="100%" />
                    </Col>
                </Row>
            </div>
        </div>
    );
};
export default Page1;
